import React, { useState, useEffect } from 'react'
import { Row, Col, Card, Statistic, Table, Progress, Tag, List, Avatar } from 'antd'
import { 
  RiseOutlined, 
  UserOutlined, 
  EyeOutlined, 
  LikeOutlined,
  BarChartOutlined 
} from '@ant-design/icons'
import { mockApi, ContentItem, StatisticData } from '@/services/mockData'
import { Link } from 'react-router-dom'


const Dashboard: React.FC = () => {
  const [contentData, setContentData] = useState<ContentItem[]>([])
  const [statisticData, setStatisticData] = useState<StatisticData[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true)
      try {
        const [content, stats] = await Promise.all([
          mockApi.getContentList(),
          mockApi.getStatisticData()
        ])
        setContentData(content)
        setStatisticData(stats)
      } catch (error) {
        console.error('获取数据失败:', error)
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [])

  const latestStats = statisticData[statisticData.length - 1] || {
    contentCount: 0,
    userCount: 0,
    viewCount: 0,
    interactionCount: 0
  }

  const statsCards = [
    {
      title: '内容总数',
      value: latestStats.contentCount,
      prefix: <BarChartOutlined />,
      color: '#1890ff'
    },
    {
      title: '用户数量',
      value: latestStats.userCount,
      prefix: <UserOutlined />,
      color: '#52c41a'
    },
    {
      title: '总浏览量',
      value: latestStats.viewCount,
      prefix: <EyeOutlined />,
      color: '#faad14'
    },
    {
      title: '互动次数',
      value: latestStats.interactionCount,
      prefix: <LikeOutlined />,
      color: '#f5222d'
    }
  ]

  const recentActivities = [
    {
      id: '1',
      title: '新用户注册',
      description: '张三加入了幸福村社群',
      time: '2分钟前',
      avatar: '张'
    },
    {
      id: '2',
      title: '内容发布',
      description: '李技术员发布了新的农业技术文章',
      time: '1小时前',
      avatar: '李'
    },
    {
      id: '3',
      title: '互动活动',
      description: '乡村旅游推广活动获得100+参与',
      time: '3小时前',
      avatar: '旅'
    }
  ]

  const handleContentClick = (content: ContentItem) => {
    // 可以根据需要实现内容点击后的操作
    console.log('查看内容:', content.title)
  }

  const handleActivityClick = (activity: typeof recentActivities[0]) => {
    // 可以根据需要实现活动点击后的操作
    console.log('查看活动:', activity.title)
  }

  const contentColumns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      render: (text: string) => (
        <span style={{ fontWeight: 500, cursor: 'pointer' }}>{text}</span>
      )
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => {
        const typeMap = {
          article: { color: 'blue', text: '文章' },
          video: { color: 'red', text: '视频' },
          audio: { color: 'orange', text: '音频' },
          image: { color: 'green', text: '图片' }
        }
        const config = typeMap[type as keyof typeof typeMap]
        return <Tag color={config.color}>{config.text}</Tag>
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap = {
          published: { color: 'success', text: '已发布' },
          draft: { color: 'default', text: '草稿' },
          reviewing: { color: 'processing', text: '审核中' }
        }
        const config = statusMap[status as keyof typeof statusMap]
        return <Tag color={config.color}>{config.text}</Tag>
      }
    },
    {
      title: '浏览量',
      dataIndex: 'views',
      key: 'views',
      render: (views: number) => (
        <span style={{ color: '#1890ff', fontWeight: 500 }}>{views.toLocaleString()}</span>
      )
    },
    {
      title: '互动率',
      key: 'interactionRate',
      render: (record: ContentItem) => {
        const rate = record.views > 0 ? ((record.likes + record.shares) / record.views) * 100 : 0
        return <Progress percent={Math.round(rate)} size="small" />
      }
    }
  ]

  return (
    <div>
      <div className="page-title">
        <RiseOutlined />
        工作台
      </div>
      
      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        {statsCards.map((card, index) => (
          <Col xs={24} sm={12} lg={6} key={index}>
            <Card 
              className="stats-card" 
              style={{ background: card.color }}
            >
              <Statistic
                title={card.title}
                value={card.value}
                prefix={card.prefix}
                valueStyle={{ color: 'white' }}
              />
            </Card>
          </Col>
        ))}
      </Row>

      <Row gutter={[16, 16]}>
        {/* 最新内容 */}
        <Col xs={24} lg={16}>
          <Card 
            title="最新内容" 
            className="custom-card"
            extra={<Link to="/content-center">查看全部</Link>}
          >
            <Table
              dataSource={contentData}
              columns={contentColumns}
              pagination={false}
              loading={loading}
              size="small"
              rowKey="id"
              onRow={(record) => ({
                onClick: () => handleContentClick(record)
              })}
            />
          </Card>
        </Col>

        {/* 最近活动 */}
        <Col xs={24} lg={8}>
          <Card title="最近活动" className="custom-card">
            <List
              dataSource={recentActivities}
              renderItem={(item) => (
                <List.Item
                  key={item.id}
                  onClick={() => handleActivityClick(item)}
                  style={{ cursor: 'pointer' }}
                >
                  <List.Item.Meta
                    avatar={<Avatar>{item.avatar}</Avatar>}
                    title={
                      <div style={{ fontWeight: 500 }}>{item.title}</div>
                    }
                    description={
                      <div>
                        <div>{item.description}</div>
                        <div style={{ color: '#999', fontSize: 12 }}>{item.time}</div>
                      </div>
                    }
                  />

                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>
    </div>
  )
}

export default Dashboard